package com.guiji.quartz.domain;

import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.wanghaomiao.xpath.model.JXDocument;
import com.guiji.quartz.task.DataSaveUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @program: cms-vue-plus
 * @description:
 * @author: wangxiaowen
 * @create: 2021-11-12 18:05
 **/
public class ChinaOrgBusiness {
	private static final Logger log = LoggerFactory.getLogger(ChinaOrgBusiness.class);

	public static void mainMethod() throws Exception {
		HttpResponse response = null;
		String doc;
		JXDocument jxDocument = null;
		try {
			response = HttpRequest.get("http://www.china.org.cn/business/index.htm")
				.header("Accept", "*/*")
				.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36")
				.header("Accept-Encoding", "gzip, deflate, br")
				.header("Accept-Language", "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7")
				.setConnectionTimeout(15000)
				.execute();
			doc = response.body();
			jxDocument = new JXDocument(doc);
		} catch (Exception e) {
			log.error("http://www.china.org.cn/business/index.htm 代理失败1" + e);
			return;
		}


		String to_list_url = null;
		try {
			to_list_url = (String) jxDocument.sel("//div[@class='columns2']/p/a/@href").get(0);
		} catch (Exception e) {
			log.error("to_list_url-------------" + to_list_url + "-------------------to_list_url");
		}

		if (null != to_list_url) {
			HttpResponse response1 = null;
			String doc1;
			JXDocument jxDocument1 = null;
			to_list_url = to_list_url.strip();
			try {
				response1 = HttpRequest.get(to_list_url)
					.header("Accept", "*/*")
					.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36")
					.header("Accept-Encoding", "gzip, deflate, br")
					.header("Accept-Language", "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7")
					.setConnectionTimeout(15000)
					.execute();

				String resp = response1.body();
				Set<String> resUrl = getUrl(resp);
				getContent(resUrl);
			} catch (Exception e) {
				log.error(to_list_url + " 代理失败1" + e);
				return;
			}


		}

	}

	private static void getContent(Set<String> listContent) throws InterruptedException {
		for (String url : listContent) {
			Thread.sleep(1000);
			log.info("getContent执行到-{},listContent长度-{}", url, listContent.size());
			String doc = null;
			JXDocument jxDocument = null;
			try {

				HttpResponse response = HttpRequest.get(url)
					.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36")
					.setConnectionTimeout(15000).execute();
				doc = response.body();
				jxDocument = new JXDocument(doc);
			} catch (HttpException e) {
				log.info("请求详情页失败" + e);
			}
			String title;
			try {
				title = (String) jxDocument.sel("//h1[@id='title']/text()").get(0);
			} catch (Exception e) {
				log.error("标题错误-------------" + url + "-------------------标题错误");
				continue;
			}

			StringBuffer content = new StringBuffer();
			String contentStr = null;
			try {
				jxDocument.sel("//div[@id='container_txt']//p/text()").forEach(s -> {
					content.append(s + "$$$");
				});

				contentStr = content.toString();
			} catch (Exception e) {
				continue;
			}

			String img = null;
			try {
				int imgSize = jxDocument.sel("//img/@src").size();
				if (imgSize > 0) {
					String temp = null;
					for (int k = 0; k < imgSize; k++) {
						temp = jxDocument.sel("//img/@src").get(k).toString();
						if (temp != null && temp.contains("http://images.china.cn/site")) {
							img = temp.strip();
							break;
						}
					}
				}

			} catch (Exception e) {
				log.error("可能没有图片");
				img = "";
			}

			Date date = new Date();
			List<Object> newImgs = new ArrayList<>();
			if (null != img) {
				newImgs.add(img);
			}


			if (contentStr.length() > 50000 || contentStr.toString().replaceAll("\\$|[\\s\\p{Zs}]", "").length() < 20 || newImgs.size() > 20) {
				continue;
			}
			try {
				DataSaveUtil.saveData(title, content.toString(), newImgs, url, date, "http://www.china.org.cn/business/index.htm", "ChinaOrg-EnglishBusiness");
				log.info(Thread.currentThread().getName() + "-----------------china-org-business----------------");
			} catch (Exception e) {
				continue;
			}
		}
	}

	private static Set<String> getUrl(String content) {

		Set<String> res = new HashSet<>();
		String pattern = "http://www.china.org.cn/business/[0-9]{4}-[0-9]{2}/[0-9]{2}/.*?htm";
		Pattern p = Pattern.compile(pattern);
		Matcher m = p.matcher(content);
		while (m.find()) {
			res.add(m.group());
		}
		return res;
	}


}

